/**
 * 提出css中的图片地址并产生以图片内容为md5的图片文件
 * gulp 插件
 * @author Mark.Chen <sim_cn@qq.com>
 * @version 1.0.0
 */

var through2 = require('through2');
var md5File = require('md5-file');
var fs = require('fs');

var config = require('./config');

var md5img = function(str) {
    var re = /url\((.*?)\)/ig;
    str = str.replace(re, function($0, $1) {
        var img = $1.replace(/\?.*|\(|\)|\'\"/g, '');
        var ext = img.replace(/.*(\..*?)/g, "$1");
        if (img.substr(0, 5) === 'http:') {
            //远程的url直接更新时间戳
            return 'url(' + img + '?' + +new Date() + ')';
        } else {
            //本地改名并复制到新的地址
            var curFile = './' + img;
            var md5img = md5File(curFile);
            //判断文件是否存在
            var isExists = fs.existsSync(curFile);
            if (!isExists) {
                console.log(img + '_文件不存在需要处理下!');
                return 'url(' + img + ')';
            } else {
                img = config.onlineimg + '/' + md5img + ext;
                fs.readFile(curFile, function(err, data) {
                    var destImgName = config.onlinefile + md5img + ext;
                    fs.appendFile(destImgName, data);
                });
                return 'url(' + img + ')';
            }
        }
    });
    return str;
}

module.exports = function(options) {
    return through2.obj(function(file, enc, callback) {
        if (file.isNull()) {
            return callback(null, file);
        }
        var str = file.contents.toString();
        newstr = md5img(str);
        file.contents = new Buffer(newstr);
        callback(null, file);
    });
};
